import { createStore } from 'vuex'

export default createStore({
  modules: {
    user: {
      namespaced: true,
      state: {
        currentUser: null,
        favorites: []
      },
      
      mutations: {
        SET_USER(state, user) {
          state.currentUser = user
        },
        SET_FAVORITES(state, favorites) {
          state.favorites = favorites
        }
      },
      
      actions: {
        async login({ commit }, credentials) {
          // 模拟登录API调用
          const user = {
            id: 1,
            name: '旅行者',
            email: credentials.email
          }
          commit('SET_USER', user)
          localStorage.setItem('userToken', 'mock-token')
        },
        
        logout({ commit }) {
          commit('SET_USER', null)
          commit('SET_FAVORITES', [])
          localStorage.removeItem('userToken')
        },
        
        addFavorite({ commit, state }, city) {
          const favorites = [...state.favorites, city]
          commit('SET_FAVORITES', favorites)
          localStorage.setItem('userFavorites', JSON.stringify(favorites))
        },
        
        removeFavorite({ commit, state }, cityId) {
          const favorites = state.favorites.filter(city => city.id !== cityId)
          commit('SET_FAVORITES', favorites)
          localStorage.setItem('userFavorites', JSON.stringify(favorites))
        }
      },
      
      getters: {
        isCityFavorited: (state) => (cityId) => {
          return state.favorites.some(city => city.id === cityId)
        },
        favoriteCities: (state) => {
          return state.favorites
        }
      }
    }
  },
  
  state: {
    cities: [],
    searchResults: [],
    loading: false
  },
  
  mutations: {
    SET_CITIES(state, cities) {
      state.cities = cities
    },
    SET_SEARCH_RESULTS(state, results) {
      state.searchResults = results
    },
    SET_LOADING(state, loading) {
      state.loading = loading
    }
  },
  
  actions: {
    async fetchCities({ commit }) {
      commit('SET_LOADING', true)
      // 模拟API调用
      setTimeout(() => {
        const cities = [
          // 城市数据
        ]
        commit('SET_CITIES', cities)
        commit('SET_LOADING', false)
      }, 1000)
    },
    
    async search({ commit }, query) {
      commit('SET_LOADING', true)
      // 模拟搜索API调用
      setTimeout(() => {
        const results = []
        commit('SET_SEARCH_RESULTS', results)
        commit('SET_LOADING', false)
      }, 500)
    }
  },
  
  getters: {
    isLoading: (state) => state.loading,
    getCities: (state) => state.cities,
    getSearchResults: (state) => state.searchResults
  }
})